package cz.cuni.mff.ufal.volk.services;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;

public class Services {
	private Services() {
	} // makes the class "static"

	public static void setFactory(BeanFactory factory) {
		if (Services.factory != null)
			throw new IllegalStateException("An attempt was made to set the bean factory more than once");
		factory.getClass();

		Services.factory = factory;
	}

	private static BeanFactory factory;
	private static Logger log = Logger.getLogger(Services.class);
	public static final String SERVICES = "services";

	private static Map<String, Object> registeredServices;
	private final static Object servicesLock = new Object();

	@SuppressWarnings("unchecked")
  public static <T> T get(String name, Class<T> type) {
		name.getClass();
		return (T)registered().get(name);
	}

	@SuppressWarnings("unchecked")
  public static Map<String, Object> registered() {
		if (registeredServices == null) {
			synchronized (servicesLock) {
				if (registeredServices == null) {
					if (factory.containsBean(SERVICES)) {
						try {
							registeredServices = factory.getBean(SERVICES, Map.class);
						} catch (Throwable t) {
							log.error("An error occurred when trying to retrieve the " + SERVICES + " bean", t);
							registeredServices = new HashMap<String, Object>();
						}
					} else {
						registeredServices = new HashMap<String, Object>();
					}
				}
				registeredServices = Collections.synchronizedMap(registeredServices);
			}
		}
		return registeredServices;
	}

	//[start]standard names of the services

	/** Standard name of the main text to speech service. */
	public static final String TEXT_TO_SPEECH = "volk.tts";

	/** Standard name of the language recognition service. */
	public static final String LANGUAGE_RECOGNITION = "volk.langrec";

	//[end]
}
